<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SendEmail;
use App\Models\User;
use App\Models\Configuration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mockery\Exception;
use Validator;

class CompanyController extends Controller {
	private $company_id;
	private $user;
	private $role_flag;
	public function __construct() {
		$this->deviceType = $this->getDevice();
		if (\Auth::guard('api')->check()) {
			$user = \Auth::guard('api')->user();
			$data = User::find($user->id);
			if ($this->deviceType) {
//                PC
				$this->company_id = $data->company_id;
				$this->user = $data;
			} else {
//                APP
				$this->company_id = $data->appcompany_id;
				$this->user = $data;
				$this->user->company_id = $data->appcompany_id;
			}
			$company = \App\Models\Company::find($this->user->company_id);
			if (!empty($company)) {
				$this->role_flag = $company->role_flag;
			}
		}
	}

	/**
	 * 创建企业
	 * @param  $uid [用户ID]
	 * @param  $companyName [企业名称]
	 * @param  $userName [用户姓名]
	 * @param  $from [1app,2pc]
	 */
	public function createCompany(Request $request) {
		$uid = $request->input('uid');
		$userInfo = $this->user;
		$data = $request->all();
		if (empty($data)) {
			return response()->json(['code' => 400, 'msg' => '非法操作', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$cmpInfo = DB::table('companies')->where(['user_id' => $userInfo->id, 'status' => 0])->first();
		if (!empty($cmpInfo)) {
			return response()->json(['code' => 400, 'msg' => '当前账户已创建企业 ，不能重复创建', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$userName = $request->input('userName');
		$companyName = $request->input('companyName');
		$mobile = $request->input('mobile');
		$roleFlag = str_random(14) . time();
		$cmplist = DB::table('companies')->where([['user_id', '=', $userInfo->id], ['name', '=', $companyName]])->get()->toArray();
		if (!empty($cmplist)) {
			return response()->json(['code' => 400, 'msg' => '该企业已存在', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		try {
			$p = $this->initialize();
//        注册云信企业账号
			$userUid = md5($mobile);
			$companyUid = $roleFlag;
			if (empty($userInfo->accid)) {
				$icon = getenv('HTTP_URL_IMG') . $userInfo->image;
				$useResult = $p->createUserId($userUid, $userName, $props = '{}', $icon, $token = '');
				if (empty($useResult)) {
					return response()->json(['code' => 400, 'msg' => '云信账户注册失败', 'data' => ['userId' => '', 'companyId' => '']]);
				}
				if ($useResult['code'] == 414 && $useResult['desc'] == 'already register') {
					$useResult = $p->updateUserToken($userUid);
				}
				if ($useResult['code'] == 200) {
					$userAccid = $useResult['info']['accid'];
					$userToken = $useResult['info']['token'];
				} else {
					$userAccid = $userInfo->accid;
					$userToken = $userInfo->acc_token;
				}
			} else {
				$userAccid = $userInfo->accid;
				$userToken = $userInfo->acc_token;
			}
			$companyResult = $p->createUserId($companyUid, '系统', $props = '{}', $icon = '', $token = '');
			if (empty($companyResult)) {
				return response()->json(['code' => 400, 'msg' => '云信账户注册失败', 'data' => ['userId' => '', 'companyId' => '']]);
			}
		} catch (Exception $e) {
			return response()->json(['code' => 400, 'msg' => '系统异常请联系管理员', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		if ($companyResult['code'] == 414 && $companyResult['desc'] == 'already register') {
			$companyResult = $p->updateUserToken($companyUid);
		}
		if ($companyResult['code'] == 200) {
			$compayAccid = $companyResult['info']['accid'];
			$compayToken = $companyResult['info']['token'];
		} else {
			$compayAccid = "";
			$compayToken = "";
		}
		$time = time();

		try {
			DB::beginTransaction();

			$companyId = DB::table('companies')
				->insertGetId(
					['user_id' => $userInfo->id,
						'interview_assistant' => $compayAccid,
						'interview_token' => $compayToken,
						'name' => $companyName,
						'role_flag' => $roleFlag,
						'updated_at' => $time,
						'created_at' => $time,
					]
				);
			$offerTitle = '【#公司名称#】录取通知';
			$positionTitle = '#公司名称#期待您的加入';
			$interviewTitle = '面试邀请函【#公司名称#】邀请您参加【#面试职位#】的面试';
			$offerContent = '<p class="ql-align-center"><span style="color: rgb(53, 53, 53);">入职通知书</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">尊敬的#候选人姓名#：</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">非常荣幸地通知您，您已被我司正式录用，于 #入职部门# 任 #职位# 一职。真诚欢迎您的加入，并诚意地邀请您根据下述内容准时到公司报到。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一、报到事宜</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;时&nbsp;&nbsp;&nbsp;间：#入职时间#</span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;公司地址：#地址#</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">二、携带资料</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">失业证或与原单位解除劳动合同的证明材料原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">入职通知书；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">身份证；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">最高学历证明原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">其他相关学历证明；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一寸彩色免冠近期照片两张。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">三、聘用条款</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">薪&nbsp;资：试用期工资（税前） #薪资# / 元</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">四、说明</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">接受该入职邀请视为您同意承诺如下：入职前已与原工作单位解除劳动合同，并不再承担竞业禁止等相关责任；如您与原工作单位发生劳动纠纷，由您个人承担全部责任。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请您理解，此通知书具体内容为保密信息，将邀请内容披露给第三方均会导致邀请自动失效，无论您是否接受此邀请。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请尽快回复是否接受该入职邀请，否则视为放弃，我们期待您的加入。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><br></p><p>&nbsp;&nbsp;联系人：#联系人#</p><p><br></p><p>&nbsp;&nbsp;联系电话：#联系电话#</p><p><br></p><p>	<span style="color: rgb(53, 53, 53);">#公司名称#</span></p>';
			$positionContent = '<p><span style="color: rgb(53, 53, 53);">尊敬的#候选人姓名#：</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;您好，我们公司最近有新的职位正在进行招聘，您的简历和我们的职位比较匹配，#公司名称#期待您的加入。</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;如果您有意向，可以回复邮件至：****@163.com，或者致电：029:88888888。</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;您也可以在我公司官网投递简历</span></p>';
			$interviewContent = '<p style="text-align:center">面试通知</p><p>尊敬的#候选人姓名#：</p><p>&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;您好，很高兴您从众多的候选人中脱颖而出，特邀请您参加我公司的入职面试，具体安排如下：</p><p style="padding-left:2em">&nbsp;&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;应聘职位：#面试职位#</p><p style="padding-left:2em">&nbsp;&nbsp;时间：#面试时间#</p><p style="padding-left:2em">&nbsp;&nbsp;地点：#面试地点#</p><p style="padding-left:2em"><br></p><p style="padding-left:2em">&nbsp;&nbsp;温馨提示：请携带您的最新个人简历。</p><p style="padding-left:2em">&nbsp;&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;如果有任何问题，您都可以通过以下方式联系确认</p><p style="padding-left:2em">&nbsp;&nbsp;联系人：#联系人#</p><p style="padding-left:2em">&nbsp;&nbsp;联系电话：#联系电话#</p><p><br></p><p>#公司名称#</p>';
			DB::table('email_sets')
				->insert([
					'user_id' => $userInfo->id,
					'company_id' => $companyId,
					'host' => '',
					'port' => '',
					'user_name' => '',
					'password' => '',
					'address' => '',
					'name' => '',
					'offer_content' => $offerContent,
					'offer_title' => $offerTitle,
					'created_at' => $time,
					'updated_at' => $time]);
			DB::table('template')
				->insert([
					'company_id' => $companyId,
					'type' => 2,
					'title' => $positionTitle,
					'content' => $positionContent,
					'created_at' => $time,
					'updated_at' => $time,
				]);
			DB::table('template')
				->insert([
					'company_id' => $companyId,
					'type' => 3,
					'title' => $interviewTitle,
					'content' => $interviewContent,
					'created_at' => $time,
					'updated_at' => $time,
				]);
			DB::commit();
		} catch (\Exception $e) {
			DB::rollback();
			return response()->json(['code' => 400, 'msg' => '创建企业失败', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		if (empty($companyId)) {
			return response()->json(['code' => 400, 'msg' => '创建企业失败', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		if ($this->deviceType) {
			$userUp = DB::table('users')
				->where('id', $userInfo->id)
				->update(['company_id' => $companyId, 'name' => $userName, 'accid' => $userAccid, 'acc_token' => $userToken, 'created_at' => time()]);
		} else {
			$userUp = DB::table('users')
				->where('id', $userInfo->id)
				->update(['appcompany_id' => $companyId, 'name' => $userName, 'accid' => $userAccid, 'acc_token' => $userToken, 'created_at' => time()]);
		}
		if (empty($userUp)) {
			return response()->json(['code' => 400, 'msg' => '创建企业失败', 'data' => ['userId' => '', 'companyId' => '']]);
		}
		$this->initBaseData($request);

		$depId = DB::table('departments')
			->where([['company_id', '=', $companyId], ['depth', '=', 1]])
			->select('id')
			->first();
		if (empty($depId)) {
			$depId = "";
		} else {
			$depId = $depId->id;
		}
		return response()->json(['code' => 200, 'msg' => '创建企业成功', 'data' => ['userId' => $userInfo->id, 'companyId' => $companyId, 'accid' => $userAccid, 'accToken' => $userToken, 'depId' => $depId]]);
	}

	/**
	 * 企业列表
	 * @param  $uid [用户ID ]
	 * @param  $mobile [手机号]
	 * @param  $page [分页]
	 */
	public function companyList(Request $request) {
		$data = $request->all();
		$mobile = $request->input('mobile');
		$pages = $request->input('page');
		if (empty($pages)) {
			$list = DB::table('staff')
				->join('companies', 'staff.company_id', '=', 'companies.id')
				->where([['staff.mobile', '=', $mobile], ['staff.status', '=', '0']])
				->select('staff.company_id as cid', 'staff.name as userName', 'staff.status', 'companies.name as companyName')
				->orderBy('cid', 'desc')
				->get();
			$num = 0;
		} else {
//            $page = $request->input('page') ? $request->input('page') : 1;
			//            $pageNum = $request->input('perPage') ? $request->input('perPage') : 6;
			//            $skip = ($page - 1) * $pageNum;
			//            $take = $pageNum;
			$list = DB::table('staff')
				->join('companies', 'staff.company_id', '=', 'companies.id')
				->where([['staff.mobile', '=', $mobile], ['staff.status', '=', '0']])
				->select('staff.company_id as cid', 'staff.name as userName', 'staff.status', 'companies.name as companyName')
//                ->skip($skip)
			//                ->take($take)
				->orderBy('cid', 'desc')
				->get();
			$count = DB::table('staff')
				->join('companies', 'staff.company_id', '=', 'companies.id')
				->where([['staff.mobile', '=', $mobile], ['staff.status', '=', '0']])
				->count();
			$num = ceil($count / 6);
		}
		if (!empty($list->toArray())) {
			$type = 1;
		} else {
			$type = 0;
		}
		return response()->json(['code' => 200, 'msg' => '成功', 'data' => ['list' => $list, 'type' => $type, 'num' => $num]]);
	}

	/**
	 * 加入企业
	 * @param  $uid [用户ID ]
	 * @param  $cid [手机号]
	 */
	public function choseCompany(Request $request) {
		$uid = $request->input('uid');
		$cid = $request->input('cid');
		$userName = $request->input('userName');
		$userInfo = User::where('id', $uid)->first();
		$time = time();

		if (empty($userInfo)) {
			return response()->json(['code' => 400, 'msg' => '不存在该用户', 'data' => '']);
		}
		$comapnyInfo = DB::table('companies')->where('id', $cid)->first();
		if (empty($comapnyInfo)) {
			return response()->json(['code' => 400, 'msg' => '不存在该公司', 'data' => '']);
		}
		$count = DB::table('staff')->where([['company_id', $cid], ['user_id', '!=', 0],['status', '!=', 1]])->count();
		$msg = '请联系该企业管理员购买软件';
        $typeInfo = DB::table('staff')->where(['company_id'=>$cid,'mobile'=>$userInfo->mobile,'status'=>0])->first();
        $number = $config = Config::get('info.number');
        if(empty($typeInfo->user_id)){
            $count += 1;
        }
		if ($count > $number+$comapnyInfo->order_num) {
		    if($userInfo->id != $comapnyInfo->user_id){
                return response()->json(['code' => 400, 'msg' => $msg, 'data' => '']);
            }
		}
		if(!empty($comapnyInfo->order_updated_at) && time()>=$comapnyInfo->order_updated_at){
            if($userInfo->id != $comapnyInfo->user_id){
                return response()->json(['code' => 400, 'msg' => $msg, 'data' => '']);
            }
        }
		$mobile = $userInfo->mobile;
		if (empty($userInfo->accid)) {
			try {
				$p = $this->initialize();
//        注册云信
				$userUid = md5($mobile);
				$icon = getenv('HTTP_URL_IMG') . $userInfo->image;
				$useResult = $p->createUserId($userUid, $userName, $props = '{}', $icon, $token = '');
				if (empty($useResult)) {
					return response()->json(['code' => 400, 'msg' => '云信账户注册失败', 'data' => ['userId' => '', 'companyId' => '']]);
				}
			} catch (Exception $e) {
				return response()->json(['code' => 400, 'msg' => '系统异常请联系管理员', 'data' => ['userId' => '', 'companyId' => '']]);
			}
			if ($useResult['code'] == 414 && $useResult['desc'] == 'already register') {
				$useResult = $p->updateUserToken($userUid);
			}

			if ($useResult['code'] == 200) {
				$userAccid = $useResult['info']['accid'];
				$userToken = $useResult['info']['token'];
			} else {
				$userAccid = '';
				$userToken = '';
			}
			if ($this->deviceType) {
				$userUp = DB::table('users')
					->where('id', $uid)->update(['company_id' => $cid, 'name' => $userName, 'accid' => $userAccid, 'acc_token' => $userToken, 'updated_at' => $time]);
			} else {
				$userUp = DB::table('users')
					->where('id', $uid)->update(['appcompany_id' => $cid, 'name' => $userName, 'accid' => $userAccid, 'acc_token' => $userToken, 'updated_at' => $time]);
			}
		} else {
			if ($this->deviceType) {
				$userUp = User::where('id', $uid)
					->where('id', $uid)
					->update(['company_id' => $cid, 'name' => $userName]);
				\Log::info('1' . $userUp);
			} else {
				$userUp = User::where('id', $uid)
					->update(['appcompany_id' => $cid, 'name' => $userName]);
				\Log::info('2' . $userUp);
			}
		}
		if ($userUp === false) {
			return response()->json(['code' => 400, 'msg' => '选择企业失败', 'data' => '']);
		}
		DB::table('staff')->where(['company_id' => $cid, 'mobile' => $mobile])->update(['user_id' => $userInfo->id, 'updated_at' => $time]);
		$userInfo = User::where('id', $uid)->first();
		$device = $this->getDevice();
		if(!$device){
		    $userInfo->company_id = $userInfo->appcompany_id;
        }
		return response()->json(['code' => 200, 'msg' => '选择企业成功', 'data' => ['accid' => $userInfo->accid, 'accToken' => $userInfo->acc_token, 'uid' => $userInfo->id, 'cid' => $userInfo->company_id]]);
	}

//    初始化云信
	protected function initialize() {
		$config = Config::get('info.yunim');
		$appKey = $config['Appkey'];
		$appSecret = $config['appSecret'];
		$p = new ServerapiController($appKey, $appSecret, 'curl');
		return $p;
	}

	//所有流程、所有步骤
	public function all(Request $request) {
		$user = $this->user;
		$flowInfo = DB::table('flows')
			->where([['company_id', '=', $user->company_id], ['status', '=', '0']])
			->get();
		$steps = array();
		foreach ($flowInfo as $k => $item) {
			$ss = DB::table('steps')
				->where(['flow_id' => $item->id, 'status' => 0])
				->select('flow_id as flowId', 'id', 'name as stepName')
				->get();
			foreach ($ss as $v => $s) {
				$stepName = '%,' . $s->id . ',%';
				$stepInfo = DB::table('evaluaties')->where('step_id', 'like', $stepName)->where('status', 0)->first();
				if (empty($stepInfo)) {
					$s->status = 1;
				} else {
					$s->status = 0;
				}
			}
			$steps[$k]['flowName'] = $item->name;
			$steps[$k]['item'] = $ss;
		}
		return response()->json(['code' => 200, 'msg' => '请求数据成功', 'data' => ['info' => $steps]]);
	}

//    新增、修改评价表
	public function addEvaluaty(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$id = $request->input('evalInfo')['id'];
		if (empty($id)) {
			$roleType = $request->input('roleType');
			if ($roleType == 1) {
				if (!empty($staff) && $staff->company_id == $user->company_id) {
					if (!$user->can('evaluate_add') && !$user->hasRole('管理员')) {
						return $this->respond('no_auth');
					}
				} else {
					if (!$user->can('evaluate_add')) {
						return $this->respond('no_auth');
					}
				}
				return $this->respond('op_ok');
			}
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('evaluate_add') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('evaluate_add')) {
					return $this->respond('no_auth');
				}
			}
		} else {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('evaluate_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('evaluate_edit')) {
					return $this->respond('no_auth');
				}
			}
		}
		$info = $request->input('evalInfo')['steps'];
		$evaluatyTitle = $request->input('evalInfo')['name'];
		$titleInfo = $request->input('problem');
		$time = time();
		$user = $this->user;
		$count = 0;
		foreach ($titleInfo as $item) {
			foreach ($item['item'] as $k) {
				$count += $k['weight'];
			}
		}
		if ($count > 100) {
			return response()->json(['code' => 400, 'msg' => '评价总分大于100', 'data' => '']);
		}
		if ($count < 100) {
			return response()->json(['code' => 400, 'msg' => '评价总分小于100', 'data' => '']);
		}
		$flowArray = [];
		foreach ($info as $item) {
			$result = DB::table('steps')->where('id', $item)->first();
			if (!in_array($result->flow_id, $flowArray)) {
				$flowArray[] = $result->flow_id;
			}
		}
		$flowName = "11";
		$stepName = "22";
		$belongFlow = ',' . implode(',', $flowArray) . ',';
		$belongStep = ',' . implode(',', $info) . ',';
		DB::beginTransaction();
		try {
			if (empty($id)) {
				$evalId = DB::table('evaluaties')
					->insertGetId([
						'flow_id' => $belongFlow,
						'step_id' => $belongStep,
						'company_id' => $user->company_id,
						'user_id' => $user->id,
						'name' => $evaluatyTitle,
						'belong_flow' => $flowName,
						'belong_step' => $stepName,
						'owner_name' => $user->name,
						'created_at' => $time,
						'updated_at' => $time]);
				foreach ($titleInfo as $item => $value) {
					$titleId = DB::table('titles')
						->insertGetId([
							'evaluate_id' => $evalId,
							'name' => $value['flowName'],
							'created_at' => $time,
							'updated_at' => $time]);
					foreach ($value['item'] as $k => $v) {
						DB::table('subjects')
							->insert(['title_id' => $titleId,
								'name' => $v['name'],
								'weight' => $v['weight'],
								'created_at' => $time,
								'updated_at' => $time]);
					}
				}
				DB::commit();
			} else {
				foreach ($titleInfo as $item) {
					DB::table('subjects')->where('title_id', $item['item'][0]['titleId'])->update(['status' => 1]);
				}
				DB::table('evaluaties')->where('id', $id)->update(['status' => 1]);
				DB::table('titles')->where('evaluate_id', $id)->update(['status' => 1]);
				$evalId = DB::table('evaluaties')
					->insertGetId([
						'flow_id' => $belongFlow,
						'step_id' => $belongStep,
						'company_id' => $user->company_id,
						'user_id' => $user->id,
						'name' => $evaluatyTitle,
						'belong_flow' => $flowName,
						'belong_step' => $stepName,
						'owner_name' => $user->name,
						'created_at' => $time,
						'updated_at' => $time]);
				foreach ($titleInfo as $item => $value) {
					$titleId = DB::table('titles')
						->insertGetId([
							'evaluate_id' => $evalId,
							'name' => $value['flowName'],
							'created_at' => $time,
							'updated_at' => $time]);
					foreach ($value['item'] as $k => $v) {
						DB::table('subjects')
							->insert(['title_id' => $titleId,
								'name' => $v['name'],
								'weight' => $v['weight'],
								'created_at' => $time,
								'updated_at' => $time]);
					}
				}
				DB::commit();
			}
		} catch (\Exception $e) {
			DB::rollback(); //事务回滚
			return response()->json(['code' => 400, 'msg' => '操作失败', 'data' => '']);
		}
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
	}
//评价表删除
	public function evaluatyRemove(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('evaluate_remove') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('evaluate_remove')) {
				return $this->respond('no_auth');
			}
		}
		$userInfo = $user;
		$info = $request->input('info');
		DB::beginTransaction();
		try {
			foreach ($info as $item) {
				$flows = explode(',', trim($item['flows'], ','));
				$check_status = DB::table('resumes')
					->where(['company_id' => $userInfo->company_id, 'status' => 0])
					->whereIn('flow_id', $flows)
					->first();
				if (!empty($check_status)) {
					$get_status = DB::table('resumes')
						->select(DB::raw('select id from resumes where company_id = $userInfo->company_id step_id>=1 and ask_status!=2 and (check_status=0||check_status=3) and status=0 limit 1'));
					if (!empty($get_status)) {
						DB::rollback();
						return response()->json(['code' => 400, 'msg' => '评价表使用中,不允许删除！']);
					}
				}
				DB::table('evaluaties')->where('id', $item['id'])->update(['status' => 1]);
			}
			DB::commit();
			return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
		} catch (\Exception $e) {
			DB::rollback(); //事务回滚
			return response()->json(['code' => 400, 'msg' => '操作失败', 'data' => '']);
		}
	}
//    评价表列表
	public function evaluatyList(Request $request) {
		$userInfo = $this->user;
		$title = $request->input('title');
		$page = $this->page($request);
		if (empty($title) && $title != 0) {
			$listInfo = DB::table('evaluaties')
				->where([['company_id', '=', $userInfo->company_id], ['status', '=', 0]])
				->select('id', 'flow_id as flows', 'step_id as steps', 'name as title', 'belong_flow as flowName', 'belong_step as stepName', 'owner_name as name', 'created_at as time')
				->skip($page['skip'])
				->take($page['take'])
				->orderBy('id', 'desc')
				->get();
			$count = DB::table('evaluaties')
				->where([['company_id', '=', $userInfo->company_id], ['status', '=', 0]])
				->count();
			$num = ceil($count / $page['take']);
		} else {
			$name = '%' . $title . '%';
			$listInfo = DB::table('evaluaties')
				->where([['company_id', '=', $userInfo->company_id], ['name', 'like', $name], ['status', '=', 0]])
				->select('id', 'flow_id as flows', 'step_id as steps', 'name as title', 'belong_flow as flowName', 'belong_step as stepName', 'owner_name as name', 'created_at as time')
				->skip($page['skip'])
				->take($page['take'])
				->orderBy('id', 'desc')
				->get();
			$count = DB::table('evaluaties')
				->where([['company_id', '=', $userInfo->company_id], ['name', 'like', $name], ['status', '=', 0]])
				->count();
			$num = ceil($count / $page['take']);
		}
		foreach ($listInfo as $item) {
			$steps = explode(',', trim($item->steps, ','));
			$number = DB::table('answers')
				->where('resume_id', $item->id)
				->count();
//            $number = DB::table('flow_histories')
			//                ->whereIn('step_id', $steps)
			//                ->where([['ask_status','=',1],['check_status','!=',0]])
			//                ->count();
			$item->number = $number;
			$flows = explode(',', trim($item->flows, ','));
			$flowName = DB::table('flows')
				->whereIn('id', $flows)
				->where('status', 0)
				->pluck('name')
				->toArray();
			$item->flowName = implode('、', $flowName);
			foreach ($flows as $k => $v) {
				$stepName = DB::table('steps')
					->whereIn('id', $steps)
					->where([['status', 0], ['flow_id', '=', $v]])
					->pluck('name')
					->toArray();
				$flowsName = DB::table('flows')->where('id', $v)->select('name')->first();
				$str[] = $flowsName->name . '(' . implode(',', $stepName) . ')';
			}
			$item->stepName = implode('、', $str);
			$str = array();
		}
		return response()->json(['code' => 200, 'msg' => '数据请求成功', 'data' => ['info' => $listInfo, 'count' => $count, 'num' => $num]]);
	}

	//评价表详情
	public function infoEvaluaty(Request $request) {
		$evalId = $request->input('id');
		$evalInfo = DB::table('evaluaties')
			->where('id', $evalId
			)
			->select('id', 'flow_id as flows', 'step_id as steps', 'name')
			->first();
		$evalInfo->flows = trim(trim($evalInfo->flows, ','));
		$evalInfo->steps = trim(trim($evalInfo->steps, ','));
		$evalInfo->flows = explode(',', $evalInfo->flows);
		$evalInfo->steps = explode(',', $evalInfo->steps);
		$titleInfo = DB::table('titles')
			->where([['evaluate_id', $evalInfo->id], ['status', 0]])
			->get();
		if (empty($titleInfo->toArray())) {
			$problem = array();
		} else {
			foreach ($titleInfo as $k => $item) {

				$subInfo = DB::table('subjects')
					->join('titles', 'subjects.title_id', '=', 'titles.id')
					->where([['subjects.title_id', $item->id], ['subjects.status', 0]])
					->select('titles.name as title', 'subjects.id', 'subjects.title_id as titleId', 'subjects.name', 'subjects.weight')
					->orderBy('subjects.id', 'asc')
					->get()
					->toArray();

				$problem[$k]['flowName'] = $item->name;
				$problem[$k]['item'] = $subInfo;
			}
		}
		return response()->json(['code' => 200, 'msg' => '数据请求成功', 'data' => ['evalInfo' => $evalInfo, 'problem' => $problem]]);
	}

//    面试地点新增、修改
	public function addAddress(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('address_set') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('address_set')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('address_set') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('address_set')) {
				return $this->respond('no_auth');
			}
		}
		$info = $request->input('info');
		$userInfo = $this->user;
		$time = time();
		if (empty($info)) {
			return response()->json(['code' => 400, 'msg' => '数据格式错误', 'data' => '']);
		}
		try {
			DB::table('addresses')->where('company_id', $userInfo->company_id)->update(['status' => 1]);
			foreach ($info as $item) {
				if (empty($item['address'])) {
					return response()->json(['code' => 400, 'msg' => '地址不能为空', 'data' => '']);
				}
				$info = DB::table('addresses')
					->where([['address', '=', $item['address']], ['status', '=', 0], ['company_id', '=', $userInfo->company_id]])
					->first();
				if (!empty($info)) {
					return response()->json(['code' => 400, 'msg' => '面试地址重复', 'data' => '']);
				}
				DB::table('addresses')
					->insert(['user_id' => $userInfo->id,
						'company_id' => $userInfo->company_id,
						'address' => $item['address'],
						'created_at' => $time,
						'updated_at' => $time]);
			}
			return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
		} catch (\Exception $e) {
			Log::info('面试地址操作失败 ' . $e->getMessage());
			return response()->json(['code' => 400, 'msg' => '操作失败', 'data' => '']);
		}
	}

//    面试地址列表
	public function addressList(Request $request) {
		$userInfo = $this->user;
		$result = DB::table('addresses')
			->where([['company_id', $userInfo->company_id], ['status', 0], ['address', '<>', '其他']])
			->select('id', 'address')
			->get()
			->toArray();
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => ['info' => $result]]);
	}

//    邮件配置新增与修改
	public function addMail(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_email_set') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_email_set')) {
				return $this->respond('no_auth');
			}
		}
		$id = $request->input('id');
		$userInfo = $this->user;
		$isUse = $request->input('isOn') ?? 1;
		$fromCom = $request->input('fromCom');
		$send = $request->input('send');
		$smtpServer = $request->input('smtpServer');
		$smtpPort = $request->input('smtpPort');
		$smtpType = $request->input('smtpType');
		$smtpUser = $request->input('smtpUser');
		$smtpPwd = $request->input('smtpPwd');
		$time = time();
		if (empty($id)) {
			$result = DB::table('email_sets')
				->insert([
					'user_id' => $userInfo->id,
					'company_id' => $userInfo->company_id,
					'host' => $smtpServer,
					'port' => $smtpPort,
					'user_name' => $smtpUser,
					'password' => $smtpPwd,
					'address' => $fromCom,
					'name' => $send,
					'type' => $smtpType,
					'is_use' => $isUse,
					'offer_content' => '<p class="ql-align-center"><span style="color: rgb(53, 53, 53);">入职通知书</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">尊敬的#候选人姓名#：</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">非常荣幸地通知您，您已被我司正式录用，于 #入职部门# 任 #职位# 一职。真诚欢迎您的加入，并诚意地邀请您根据下述内容准时到公司报到。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一、报到事宜</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;时&nbsp;&nbsp;&nbsp;间：#入职时间#</span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;公司地址：#地址#</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">二、携带资料</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">失业证或与原单位解除劳动合同的证明材料原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">入职通知书；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">身份证；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">最高学历证明原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">其他相关学历证明；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一寸彩色免冠近期照片两张。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">三、聘用条款</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">薪&nbsp;资：试用期工资（税前） #薪资# / 元</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">四、说明</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">接受该入职邀请视为您同意承诺如下：入职前已与原工作单位解除劳动合同，并不再承担竞业禁止等相关责任；如您与原工作单位发生劳动纠纷，由您个人承担全部责任。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请您理解，此通知书具体内容为保密信息，将邀请内容披露给第三方均会导致邀请自动失效，无论您是否接受此邀请。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请尽快回复是否接受该入职邀请，否则视为放弃，我们期待您的加入。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><br></p><p>&nbsp;&nbsp;联系人：#联系人#</p><p><br></p><p>&nbsp;&nbsp;联系电话：#联系电话#</p><p><br></p><p>	<span style="color: rgb(53, 53, 53);">#公司名称#</span></p>',
					'created_at' => $time,
					'updated_at' => $time]);
		} else {
			$result = DB::table('email_sets')
				->where('id', $id)
				->update([
					'host' => $smtpServer,
					'port' => $smtpPort,
					'user_name' => $smtpUser,
					'password' => $smtpPwd,
					'address' => $fromCom,
					'type' => $smtpType,
					'is_use' => $isUse,
					'name' => $send,
					'updated_at' => $time]);
		}
		if ($result) {
			return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
		} else {
			return response()->json(['code' => 400, 'msg' => '操作失败', 'data' => '']);
		}
	}
	//    邮件配置查询
	public function mailInfo(Request $request) {
		$userInfo = $this->user;
		$result = DB::table('email_sets')
			->where('company_id', $userInfo->company_id)
			->select('id', 'host as smtpServer', 'port as smtpPort', 'user_name as smtpUser', 'password as smtpPwd', 'address as fromCom', 'type as smtpType', 'is_use as isOn', 'name as send')
			->first();
		if (empty($result)) {
			$result['id'] = '';
			$result['smtpServer'] = '';
			$result['smtpPort'] = '';
			$result['smtpUser'] = '';
			$result['smtpPwd'] = '';
			$result['fromCom'] = '';
			$result['smtpType'] = 1;
			$result['isOn'] = 1;
			$result['send'] = '';
		}
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => ['res' => $result]]);
	}
//    offer模板
	public function offerTemplate(Request $request) {

		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('offer_set') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('offer_set')) {
				return $this->respond('no_auth');
			}
		}
		$id = $request->input('id');
		$title = $request->input('title');
		$content = $request->input('content');
		$type = $request->input('type');
//        $name = strpos($content, '#候选人姓名#');
		//        $dept =  strpos($content, '#入职部门#');
		//        $position = strpos($content, '#入职岗位#');
		//        $salary = strpos($content, '#薪资#');
		//        $address = strpos($content, '#地址#');
		//        $time = strpos($content, '#入职时间#');
		//        $cmpName = strpos($content, '#公司名称#');
		//        if ($name === false || $dept === false || $position === false || $salary ===false || $address === false || $time === false || $cmpName === false) {
		//            return response()->json(['code' => 400, 'msg' => 'offer模板格式错误', 'data' => ""]);
		//        }
		$userInfo = $this->user;
		$time = time();
		if (empty($id)) {
			if ($type == 1) {
				$result = DB::table('email_sets')
					->insert([
						'user_id' => $userInfo->id,
						'company_id' => $userInfo->company_id,
						'host' => '',
						'port' => '',
						'user_name' => '',
						'password' => '',
						'address' => '',
						'name' => '',
						'offer_content' => $content,
						'offer_title' => $title,
						'created_at' => $time,
						'updated_at' => $time]);
			} else {
				$result = DB::table('template')
					->insert([
						'company_id' => $userInfo->company_id,
						'type' => $type,
						'title' => $title,
						'content' => $content,
						'created_at' => $time,
						'updated_at' => $time,
					]);
			}

		} else {
			if ($type == 1) {
				$result = DB::table('email_sets')
					->where('id', $id)
					->update([
						'offer_content' => $content,
						'offer_title' => $title,
						'updated_at' => $time]);
			} else {
				$result = DB::table('template')->where(['id' => $id, 'type' => $type])->update(['title' => $title, 'content' => $content, 'updated_at' => $time]);
			}
		}
		if ($result) {
			return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
		} else {
			return response()->json(['code' => 400, 'msg' => '操作失败', 'data' => '']);
		}
	}
	//    offer模板
	public function offerInfo(Request $request) {
		$userInfo = $this->user;
		$type = $request->input('type') ?? 1;
		$config = Config::get('info.template');
		if ($type == 1) {
			$result = DB::table('email_sets')
				->where('company_id', $userInfo->company_id)
				->select('id', 'offer_title as title', 'offer_content as content')
				->first();
			if (empty($result)) {
				$result['id'] = '';
				$result['title'] = '【#公司名称#】录取通知';
				$result['content'] = '<p class="ql-align-center"><span style="color: rgb(53, 53, 53);">入职通知书</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">尊敬的#候选人姓名#：</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">非常荣幸地通知您，您已被我司正式录用，于 #入职部门# 任 #职位# 一职。真诚欢迎您的加入，并诚意地邀请您根据下述内容准时到公司报到。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一、报到事宜</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;时&nbsp;&nbsp;&nbsp;间：#入职时间#</span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;公司地址：#地址#</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">二、携带资料</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">失业证或与原单位解除劳动合同的证明材料原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">入职通知书；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">身份证；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">最高学历证明原件；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">其他相关学历证明；</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">一寸彩色免冠近期照片两张。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">三、聘用条款</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">薪&nbsp;资：试用期工资（税前） #薪资# / 元</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">四、说明</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">接受该入职邀请视为您同意承诺如下：入职前已与原工作单位解除劳动合同，并不再承担竞业禁止等相关责任；如您与原工作单位发生劳动纠纷，由您个人承担全部责任。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请您理解，此通知书具体内容为保密信息，将邀请内容披露给第三方均会导致邀请自动失效，无论您是否接受此邀请。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><span style="color: rgb(53, 53, 53);">请尽快回复是否接受该入职邀请，否则视为放弃，我们期待您的加入。</span></p><p><span style="color: rgb(53, 53, 53);"> </span></p><p><br></p><p>&nbsp;&nbsp;联系人：#联系人#</p><p><br></p><p>&nbsp;&nbsp;联系电话：#联系电话#</p><p><br></p><p>	<span style="color: rgb(53, 53, 53);">#公司名称#</span></p>';
				$result['sign'] = $config[$type];
			} else {
				$result->sign = $config[$type];
			}
		} else {
			$result = DB::table('template')->where(['company_id' => $userInfo->company_id, 'type' => $type])->first();
			if (empty($result)) {
				if ($type == 2) {
					$result['id'] = '';
					$result['title'] = '【#公司名称#】期待您的加入';
					$result['content'] = '<p><span style="color: rgb(53, 53, 53);">尊敬的#候选人姓名#：</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;您好，我们公司最近有新的职位正在进行招聘，您的简历和我们的职位比较匹配，#公司名称#期待您的加入。</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;如果您有意向，可以回复邮件至：****@163.com，或者致电：029:88888888。</span></p><p><span style="color: rgb(53, 53, 53);"></span></p><p><span style="color: rgb(53, 53, 53);">&nbsp;&nbsp;&nbsp;&nbsp;您也可以在我公司官网投递简历</span></p>';
				} else {
					$result['id'] = '';
					$result['title'] = '【面试邀请函】【#公司名称#】邀请您参加【#面试职位#】的面试';
					$result['content'] = '<p style="text-align:center">面试通知</p><p>尊敬的#候选人姓名#：</p><p>&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;您好，很高兴您从众多的候选人中脱颖而出，特邀请您参加我公司的入职面试，具体安排如下：</p><p style="padding-left:2em">&nbsp;&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;应聘职位：#面试职位#</p><p style="padding-left:2em">&nbsp;&nbsp;时间：#面试时间#</p><p style="padding-left:2em">&nbsp;&nbsp;地点：#面试地点#</p><p style="padding-left:2em"><br></p><p style="padding-left:2em">&nbsp;&nbsp;温馨提示：请携带您的最新个人简历。</p><p style="padding-left:2em">&nbsp;&nbsp;&nbsp;</p><p style="padding-left:2em">&nbsp;&nbsp;如果有任何问题，您都可以通过以下方式联系确认</p><p style="padding-left:2em">&nbsp;&nbsp;联系人：#联系人#</p><p style="padding-left:2em">&nbsp;&nbsp;联系电话：#联系电话#</p><p><br></p><p>#公司名称#</p>';
				}
				$result['sign'] = $config[$type];
			} else {
				$result->sign = $config[$type];
			}
		}
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => ['res' => $result]]);
	}
//    发送offer
	public function sendOffer(Request $request) {
		$userInfo = $this->user;
		$id = $request->input('id');

		$mailInfo = DB::table('email_sets')
			->where('company_id', $userInfo->company_id)
			->first();
		$name = strpos($mailInfo->offer_content, '#候选人姓名#');
		if ($name === false) {
			return response()->json(['code' => 400, 'msg' => 'offer模板格式错误', 'data' => ""]);
		}
		$offerInfo = DB::table('offers')
			->where('id', $id)
			->first();
		$content = str_replace('{$name}', $offerInfo->name, $mailInfo->offer_content);
		$message = $content;
		$to = $offerInfo->email;
		$subject = 'OFFER';
		$result = $this->sendMail($message, $to, $subject);
		return $result;
	}
	//邮件测试
	public function testMail(Request $request) {
		$content = "这是一封测试邮件";
		$sub = 'test';
		$to = $request->input('to');
		$userInfo = $this->user;
		$email = DB::table('email_sets')->where('company_id',$userInfo->company_id)->first();
		if(empty($email) || (!empty($email) && empty($email->user_name))){
            return response()->json(['code' => 400, 'msg' => '邮箱未配置', 'data' =>""]);
        }
		$result = $this->sendMail($content, $to, $sub);
		return $result;
	}
//    招聘概况
	public function statistics(Request $request) {
		$userInfo = $this->user;
		$type = $request->input('type');
		$result = DB::table('flows')
			->join('steps', 'steps.flow_id', '=', 'flows.id')
			->where([['flows.company_id', $userInfo->company_id],
				['flows.is_use', '=', '1'],
				['flows.status', '=', 0]])
			->select('flows.id as fid', 'steps.id as sid', 'flows.name as fname', 'steps.name as sname')
			->get();
		switch ($type) {
		case 2:
			$startTime = strtotime(date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)));
			break;
		case 3:
			$startTime = strtotime(date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')));
			break;
		default:
			$startTime = strtotime(date('Y-m-d'));
			break;
		}
		$i = 0;
		$endTime = time();
		$list = array();
		foreach ($result as $item) {
			$list[$i]['name'] = $item->sname . '(' . $item->fname . ')';
			$count = DB::table('flow_histories')
				->where(['step_id' => $item->sid, 'status' => 0])
				->whereBetween('created_at', [$startTime, $endTime])
				->count();
			$list[$i]['count'] = $count;
			$i++;
		}
		//初审
		$firstCheck = DB::table('flow_histories')
			->where([['step_id', '=', 1], ['company_id', '=', $userInfo->company_id]])
			->whereBetween('created_at', [$startTime, $endTime])
			->count();
		$firstCheckName = DB::table('steps')
			->where('id', 1)
			->select('name')
			->first();
		//发放offer
		$sendOffer = DB::table('flow_histories')
			->where([['step_id', '=', 2], ['company_id', '=', $userInfo->company_id]])
			->whereBetween('created_at', [$startTime, $endTime])
			->count();
		$sendOfferName = DB::table('steps')
			->where('id', 2)
			->select('name')
			->first();
		//入职
		$entry = DB::table('flow_histories')
			->where([['step_id', '=', 3], ['company_id', '=', $userInfo->company_id]])
			->whereBetween('created_at', [$startTime, $endTime])
			->count();
		$entryName = DB::table('steps')
			->where('id', 3)
			->select('name')
			->first();
		//简历
		$resumes = DB::table('resumes')
			->where([['company_id', $userInfo->company_id], ['status', '=', 0]])
			->whereBetween('created_at', [$startTime, $endTime])
			->count();
		$firstCheckName = $firstCheckName->name ?? '初审';
		$sendOfferName = $sendOfferName->name ?? 'offer';
		$entryName = $entryName->name ?? '入职';
		return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => ['firstCheck' => ['name' => $firstCheckName, 'count' => $firstCheck],
			'sendOffer' => ['name' => $sendOfferName, 'count' => $sendOffer],
			'entry' => ['name' => $entryName, 'count' => $entry],
			'resumes' => ['name' => '简历', 'count' => $resumes],
			'res' => $list]]);
	}
	//面试详情列表
	public function detailsList(Request $request) {
		$userInfo = $this->user;
		$type = $request->input('type');
		$name = $request->input('name');
		switch ($type) {
		case 2:
			$startTime = strtotime(date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)));
			break;
		case 3:
			$startTime = strtotime(date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')));
			break;
		default:
			$startTime = strtotime(date('Y-m-d'));
			break;
		}
		$endTime = time();
		$page = $this->page($request);
		if (empty($name) && $name != 0) {
			$list = DB::table('flow_histories')
				->join('resumes', 'flow_histories.resume_id', '=', 'resumes.id')
				->join('users', 'flow_histories.owner_id', '=', 'users.id')
				->where([['flow_histories.company_id', '=', $userInfo->company_id], ['flow_histories.status', '=', 0]])
				->whereBetween('flow_histories.created_at', [$startTime, $endTime])
				->select('flow_histories.id', 'flow_histories.created_at as time', 'flow_histories.count', 'flow_histories.flow_name as flowName', 'flow_histories.address', 'flow_histories.admin_name as interviewer', 'users.name as askName', 'flow_histories.step_name as stepName', 'resumes.name', 'resumes.mobile', 'resumes.position')
				->skip($page['skip'])
				->take($page['take'])
				->orderBy('id', 'desc')
				->get();
			$count = DB::table('flow_histories')
				->join('resumes', 'flow_histories.resume_id', '=', 'resumes.id')
				->join('users', 'flow_histories.owner_id', '=', 'users.id')
				->where([['flow_histories.company_id', '=', $userInfo->company_id], ['flow_histories.status', '=', 0]])
				->whereBetween('flow_histories.created_at', [$startTime, $endTime])
				->count();
		} else {
			$name = '%' . $name . '%';
			$list = DB::table('flow_histories')
				->join('resumes', 'flow_histories.resume_id', '=', 'resumes.id')
				->join('users', 'flow_histories.owner_id', '=', 'users.id')
				->where([['flow_histories.company_id', '=', $userInfo->company_id], ['flow_histories.status', '=', 0], ['resumes.name', 'like', $name]])
				->whereBetween('flow_histories.created_at', [$startTime, $endTime])
				->select('flow_histories.id', 'flow_histories.created_at as time', 'flow_histories.count', 'flow_histories.flow_name as flowName', 'flow_histories.address', 'flow_histories.admin_name as interviewer', 'users.name as askName', 'flow_histories.step_name as stepName', 'resumes.name', 'resumes.mobile', 'resumes.position')
				->skip($page['skip'])
				->take($page['take'])
				->orderBy('id', 'desc')
				->get();
			$count = DB::table('flow_histories')
				->join('resumes', 'flow_histories.resume_id', '=', 'resumes.id')
				->join('users', 'flow_histories.owner_id', '=', 'users.id')
				->where([['flow_histories.company_id', '=', $userInfo->company_id], ['flow_histories.status', '=', 0], ['resumes.name', 'like', $name]])
				->whereBetween('flow_histories.created_at', [$startTime, $endTime])
				->count();
		}
		$num = ceil($count / $page['take']);
		return response()->json(['code' => 200, 'msg' => '请求成功', 'data' => ['info' => $list, 'num' => $num]]);
	}
	//面试邀请入口
	public function importInterview(Request $request) {
		$resumeId = $request->input('resumeId');
		$type = $request->input('type');
		$email = $request->input('email');
		$position = $request->input('position');
		$time = $request->input('time');
		$address = $request->input('address');
		$name = $request->input('name');
		$phone = $request->input('mobile');
		$userInfo = $this->user;
		$resume = DB::table('resumes')->where('id', $resumeId)->first();
		$cmpInfo = DB::table('companies')->where('id', $userInfo->company_id)->first();
		$template = DB::table('template')->where(['company_id' => $userInfo->company_id, 'type' => $type])->first();
		if (empty($template)) {
			return response()->json(['code' => 400, 'msg' => '面试邀请模板未配置', 'data' => '']);
		}
		$type = 1;
		$content = str_replace('#候选人姓名#', $resume->name, $template->content);
		$content = str_replace('#面试职位#', $position, $content);
		$content = str_replace('#面试时间#', $time, $content);
		$content = str_replace('#面试地点#', $address, $content);
		$content = str_replace('#联系人#', $name, $content);
		$content = str_replace('#联系电话#', $phone, $content);
		$content = str_replace('#公司名称#', $cmpInfo->name, $content);
		$message = $content;
		$to = $email;
		$title = $content = str_replace('#候选人姓名#', $resume->name, $template->title);
		$title = str_replace('#面试职位#', $position, $title);
		$title = str_replace('#面试时间#', $time, $title);
		$title = str_replace('#面试地点#', $address, $title);
		$title = str_replace('#联系人#', $name, $title);
		$title = str_replace('#联系电话#', $phone, $title);
		$title = str_replace('#公司名称#', $cmpInfo->name, $title);
		$subject = $title;
//         $result = $this->sendMail($message,$to,$subject);
		//          return $result;
		\Log::info('任务队列开始111 date' . date('Y-m-d H:i:s'));
		$this->dispatch(new SendEmail($userInfo, $message, $to, $subject,$type));
		return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => '']);
	}
//	企业招聘网站配置
    public function  configuration(Request $request){
	    $id = $request->input('id');
	    $urlName= $request->input('urlName') ?? "isnull";
	    $companyName=  $request->input('companyName') ?? "";
	    $publicity = $request->input('publicity') ?? "";
	    $logo = $request->input('logo') ?? "";
	    $banner = $request->input('banner') ?? "image/banner.png";
	    $userInfo = $this->user;
	    $time = time();
//        $validator = Validator::make($request->all(), Configuration::$rules, Configuration::$message);
//        if ($validator->fails()) {
//            return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
//        }
        if(empty($id)){
            $info = DB::table('configuration')->where('company_id',$userInfo->company_id)->first();
            if(empty($info)){
                $result  = DB::table('configuration')->insert(['user_id'=>$userInfo->id,'company_id'=>$userInfo->company_id,'url_name'=>$urlName,'company_name'=>$companyName,'logo'=>$logo,'publicity'=>$publicity,'banner'=>$banner,'created_at'=>$time,'updated_at'=>$time]);
            }else{
                $result = DB::table('configuration')->where('id',$id)->update(['url_name'=>$urlName,'company_name'=>$companyName,'logo'=>$logo,'publicity'=>$publicity,'banner'=>$banner,'updated_at'=>$time]);
            }
        }else{
            $result = DB::table('configuration')->where('id',$id)->update(['url_name'=>$urlName,'company_name'=>$companyName,'logo'=>$logo,'publicity'=>$publicity,'banner'=>$banner,'updated_at'=>$time]);
        }
        if($result){
            return response()->json(['code' => 200, 'msg' => '配置成功', 'data' =>'']);
        }else{
            return response()->json(['code' => 400, 'msg' => '配置失败', 'data' =>'']);
        }
    }
//    企业招聘网站配置查询
    public function  configurationInfo(){
	    $userInfo = $this->user;
	    $result = DB::table('configuration')->where('company_id',$userInfo->company_id)->select('id','url_name as urlName','company_name as companyName','publicity','logo','banner')->first();
	    if(empty($result)){
	        $result['id'] = '';
	        $result['companyName'] = "";
	        $result['publicity']= '';
	        $result['logo'] = '';
	        $result['banner'] = '';
        }
        return response()->json(['code' => 200, 'msg' => '查询成功', 'data' =>['info'=>$result]]);
    }
}